package com.sdx.console.order.web;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CoreDictService;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.sdx.console.order.entity.FinOrder;
import com.sdx.console.order.service.FinOrderService;
import com.sdx.console.order.web.query.FinOrderQuery;
import com.sdx.console.utils.SmsUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * FinOrder 接口
 */
@RequestMapping("/order/finOrder")
@Controller
public class FinOrderController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(FinOrderController.class);
    private static final String MODEL = "/order/finOrder";

    private static final String BOOKSMS = "SMS_164095502";

    private static final String SMS = "SMS_166095914";

    @Autowired
    FileService fileService;

    @Resource
	private FinOrderService finOrderService;

    @Resource
    private CoreDictService coreDictService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
        view.addObject("orderTypes",finOrderService.selectOrderType(2));
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("order.finOrder.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("order.finOrder.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,String orderNo) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        FinOrder finOrder = finOrderService.queryById(orderNo);
        view.addObject("finOrder", finOrder);
		setPageParam(view,request);
		try {
			view.addObject("finOrderJson", JacksonUtils.toJsonString(finOrder,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("order.finOrder.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("order.finOrder.query")
    @ResponseBody
    public JsonResult<PageQuery> list(FinOrder condtion)
    {
        PageQuery page = condtion.getPageQuery();
        finOrderService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,FinOrder finOrder,HttpServletRequest request
	) {
    	JsonResult result = JsonResult.success();
		CoreUser user = getLoginUser(request);

    	if (isNew) {
			finOrder.setUpdatedBy(user.getId().intValue());
			finOrder.setUpdatedName(user.getName());
			finOrder.setUpdatedTime(new Date());
			finOrderService.save(finOrder);
		} else {
			finOrder.setUpdatedBy(user.getId().intValue());
			finOrder.setUpdatedName(user.getName());
			finOrder.setUpdatedTime(new Date());
			finOrderService.updateTemplate(finOrder);
           try {
               //发送短信
               FinOrder order = finOrderService.queryById(finOrder.getOrderNo());
               if(order.getOrderType()==401){
                   //高粽
                   Map<String,String> param = new HashMap<>();
                   List<CoreDict> express_type = coreDictService.findAllByType("EXPRESS_TYPE");
                   String expressName = "";
                   for (CoreDict coreDict : express_type) {
                       if(coreDict.getValue().equals(order.getExpress().toString())){
                           expressName = coreDict.getName();
                           break;
                       }
                   }
                   param.put("express",expressName);
                   param.put("expressNum",finOrder.getExpressNum());
                   SendSmsResponse response = SmsUtils.sendSms(order.getContactPhone(),SMS,param);
               }else if(order.getOrderType()==411|| order.getOrderType()==996 || order.getOrderType()==997){
                   Map<String,String> param = new HashMap<>();
                   List<CoreDict> express_type = coreDictService.findAllByType("EXPRESS_TYPE");
                   String expressName = "";
                   for (CoreDict coreDict : express_type) {
                       if(coreDict.getValue().equals(order.getExpress().toString())){
                           expressName = coreDict.getName();
                           break;
                       }
                   }
                   param.put("goodsName","《"+order.getOrderName()+"》");
                   param.put("expressCompany",expressName);
                   param.put("orderNo",finOrder.getExpressNum());
                   SendSmsResponse response = SmsUtils.sendSms(order.getContactPhone(),"SMS_183797442",param);
               }else{
                   SmsUtils.expressSms(order.getContactPhone(),finOrder.getExpressNum(),BOOKSMS);
               }

           }catch (Exception e){

           }
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("order.finOrder.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)FinOrder finOrder,HttpServletRequest request
		)
    {

        return save(true,finOrder,request
		);
    }

    @PostMapping("/update.json")
    @Function("order.finOrder.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  FinOrder finOrder,HttpServletRequest request
		) {
        finOrder.setHandleStatus(2);
        finOrder.setSendTime(new Date());
		return save(false,finOrder,request
		);
    }

    @PostMapping("/finish.json")
    @Function("order.finOrder.finish")
    @ResponseBody
    public JsonResult<String> finish(@Validated(ValidateConfig.UPDATE.class)  FinOrder finOrder,HttpServletRequest request
    ) {
        finOrder.setHandleStatus(3);
        return save(false,finOrder,request
        );
    }



    @GetMapping("/view.json")
    @Function("order.finOrder.query")
    @ResponseBody
    public JsonResult<FinOrder>queryInfo(String orderNo) {
        FinOrder finOrder = finOrderService.queryById( orderNo);
        return  JsonResult.success(finOrder);
    }

    @PostMapping("/delete.json")
    @Function("order.finOrder.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        finOrderService.batchDelFinOrder(idList);
        return JsonResult.success();
    }

    @PostMapping("/excel/export.json")
    @Function("order.finOrder.export")
    @ResponseBody
    public JsonResult<String> export(HttpServletResponse response, FinOrder condtion) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此exportTestService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate = "excelTemplates/order/order.xls";
        //本次导出需要的数据
        List<FinOrder> list =finOrderService.queryByExoprt(condtion);
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            FileItem item = fileService.createFileTemp("订单信息_"+ DateUtil.now("yyyyMMddHHmmss")+".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return  JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }

    }


}
